const express = require('express');
const router = express.Router();
const Joi = require('joi');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const sharp = require('sharp');
const path = require('path');
const fs = require('fs').promises;
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const { success, error, validationError } = require('../../utils/response');

// 上传配置
const uploadDir = process.env.UPLOAD_DIR || 'public/uploads';
const maxFileSize = parseInt(process.env.MAX_FILE_SIZE) || 5 * 1024 * 1024; // 5MB
const allowedTypes = (process.env.ALLOWED_FILE_TYPES || 'jpg,jpeg,png,gif,webp').split(',');

// Multer配置
const storage = multer.memoryStorage();

const fileFilter = (req, file, cb) => {
  const ext = path.extname(file.originalname).toLowerCase().slice(1);
  if (allowedTypes.includes(ext)) {
    cb(null, true);
  } else {
    cb(new Error(`不支持的文件类型，仅支持: ${allowedTypes.join(', ')}`), false);
  }
};

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: maxFileSize
  }
});

// 生成唯一文件名
const generateFileName = (originalName) => {
  const ext = path.extname(originalName);
  const timestamp = Date.now();
  const random = Math.random().toString(36).substring(2, 8);
  return `${timestamp}-${random}${ext}`;
};

// 确保上传目录存在
const ensureUploadDir = async () => {
  try {
    await fs.access(uploadDir);
  } catch {
    await fs.mkdir(uploadDir, { recursive: true });
  }
};

// 输入验证规则
const settingsSchema = Joi.object({
  notification: Joi.boolean().optional(),
  biometricLock: Joi.boolean().optional(),
  autoBackup: Joi.boolean().optional(),
  themeColor: Joi.string().pattern(/^#[0-9A-Fa-f]{6}$/).optional(),
  fontSize: Joi.string().valid('small', 'medium', 'large').optional(),
  language: Joi.string().valid('zh-CN', 'en-US').optional()
});

const passwordSchema = Joi.object({
  oldPassword: Joi.string().required(),
  newPassword: Joi.string().min(6).max(128).required()
});

/**
 * 上传头像
 * POST /api/user/avatar
 */
router.post('/avatar', authenticateToken, upload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return validationError(res, '请选择要上传的头像');
    }

    await ensureUploadDir();

    const user_id = req.user.id;
    const filename = generateFileName(req.file.originalname);
    
    // 头像特殊处理：裁剪为正方形并压缩
    const avatarDir = path.join(uploadDir, 'avatars');
    try {
      await fs.access(avatarDir);
    } catch {
      await fs.mkdir(avatarDir, { recursive: true });
    }

    const filePath = path.join(avatarDir, filename);
    
    // 处理头像：裁剪为256x256
    await sharp(req.file.buffer)
      .resize(256, 256, { 
        fit: 'cover',
        position: 'center'
      })
      .jpeg({ quality: 90 })
      .toFile(filePath);

    // 获取文件大小
    const stats = await fs.stat(filePath);
    const avatarUrl = `/uploads/avatars/${filename}`;

    // 更新用户头像
    await req.user.update({ avatar: avatarUrl });

    return success(res, {
      url: avatarUrl,
      filename: filename,
      size: stats.size
    }, '头像上传成功', 200);

  } catch (err) {
    console.error('上传头像错误:', err);
    
    if (err.code === 'LIMIT_FILE_SIZE') {
      return error(res, '文件大小超出限制', 400);
    }
    
    if (err.message.includes('不支持的文件类型')) {
      return error(res, err.message, 400);
    }
    
    return error(res, '头像上传失败', 500);
  }
});

/**
 * 获取用户设置
 * GET /api/user/settings
 */
router.get('/settings', authenticateToken, async (req, res) => {
  try {
    const user = req.user;

    // 默认设置
    const defaultSettings = {
      notification: true,
      biometricLock: false,
      autoBackup: true,
      themeColor: '#1890ff',
      fontSize: 'medium',
      language: 'zh-CN'
    };

    // 如果用户有自定义设置，则合并
    const settings = user.settings ? { ...defaultSettings, ...user.settings } : defaultSettings;

    res.json({
      success: true,
      data: settings
    });

  } catch (error) {
    console.error('获取用户设置错误:', error);
    res.status(500).json({
      error: '服务器内部错误'
    });
  }
});

/**
 * 更新用户设置
 * PUT /api/user/settings
 */
router.put('/settings', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error, value } = settingsSchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        error: '输入数据不合法',
        details: error.details[0].message
      });
    }

    const user = req.user;

    // 获取当前设置
    const currentSettings = user.settings || {};
    
    // 合并新设置
    const newSettings = { ...currentSettings, ...value };

    // 更新用户设置
    await user.update({ settings: newSettings });

    res.json({
      success: true,
      message: '设置更新成功',
      data: newSettings
    });

  } catch (error) {
    console.error('更新用户设置错误:', error);
    res.status(500).json({
      error: '服务器内部错误'
    });
  }
});

/**
 * 修改密码
 * PUT /api/user/password
 */
router.put('/password', authenticateToken, async (req, res) => {
  try {
    // 输入验证
    const { error, value } = passwordSchema.validate(req.body);
    if (error) {
      return res.status(400).json({
        error: '输入数据不合法',
        details: error.details[0].message
      });
    }

    const { oldPassword, newPassword } = value;
    const user = req.user;

    // 获取完整用户信息（包含密码）
    const fullUser = await db.User.findByPk(user.id);

    // 验证旧密码
    const isValidPassword = await bcrypt.compare(oldPassword, fullUser.password);
    if (!isValidPassword) {
      return res.status(400).json({
        error: '原密码错误'
      });
    }

    // 加密新密码
    const saltRounds = parseInt(process.env.BCRYPT_ROUNDS) || 12;
    const hashedPassword = await bcrypt.hash(newPassword, saltRounds);

    // 更新密码
    await fullUser.update({ password: hashedPassword });

    res.json({
      success: true,
      message: '密码修改成功'
    });

  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      error: '服务器内部错误'
    });
  }
});

/**
 * 注销账户
 * DELETE /api/user/account
 */
router.delete('/account', authenticateToken, async (req, res) => {
  try {
    const { password, reason } = req.body;

    if (!password) {
      return res.status(400).json({
        error: '请输入密码确认'
      });
    }

    const user = req.user;

    // 获取完整用户信息（包含密码）
    const fullUser = await db.User.findByPk(user.id);

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, fullUser.password);
    if (!isValidPassword) {
      return res.status(400).json({
        error: '密码错误'
      });
    }

    // 开启事务，删除用户及其相关数据
    await db.sequelize.transaction(async (transaction) => {
      // 删除用户的日记（级联删除会自动处理相关的图片、标签关联等）
      await db.Diary.destroy({
        where: { user_id: user.id },
        transaction
      });

      // 删除用户的分类
      await db.Category.destroy({
        where: { user_id: user.id },
        transaction
      });

      // 删除用户的标签
      await db.Tag.destroy({
        where: { user_id: user.id },
        transaction
      });

      // 删除用户的图片
      await db.Image.destroy({
        where: { user_id: user.id },
        transaction
      });

      // 记录注销原因（可选）
      if (reason) {
        console.log(`用户 ${user.username} 注销账户，原因: ${reason}`);
      }

      // 最后删除用户账户
      await fullUser.destroy({ transaction });
    });

    res.json({
      success: true,
      message: '账户注销成功'
    });

  } catch (error) {
    console.error('注销账户错误:', error);
    res.status(500).json({
      error: '服务器内部错误'
    });
  }
});

module.exports = router; 